/**    
* @Title: RomoteRepository.java  
* @Package com.kaver.spring   
* @author roc   
* @date 2019年1月30日 下午4:59:58  
* @version V1.0  
* @copyright kaver 
*/
package com.kaver.spring;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.kaver.bean.ConfigItem;
import com.kaver.bean.FetchDto;
import com.kaver.utils.HttpUtil;

/**  
* @ClassName: RomoteRepository  
* @Description:   远程配置
* @author roc  
* @date 2019年1月30日 下午4:59:58  
*    
*/
public class RomoteRepository extends AbstractConfRepository{
	private final static Logger logger = LoggerFactory.getLogger(RomoteRepository.class);
	private static  RomoteRepository instance = new RomoteRepository();
	
	private static boolean isenable = true;
	
	public static boolean isEnable() {
		return isenable;
	}
	public static void setEnable(boolean isenable) {
		RomoteRepository.isenable =  isenable;
	}
	public static RomoteRepository getInstance() {
		return instance;
	}
	@Override
	public void load() throws Exception {
		logger.debug("加载远程配置");
		covertProperty(dohttp());
		logger.debug("加载远程配置成功");
	}
	
	private FetchDto dohttp() {
		Map<String, String> params = new HashMap<>();
		params.put("appName", AppInstance.getAppName());
		params.put("env", AppInstance.getEnv());
		try {
			String json = HttpUtil.doPost(params, new HashMap<>(), AppInstance.getServerUrl() + "/fetch");
			FetchDto fetchDto   = JSON.parseObject(json, FetchDto.class);
			return fetchDto;
		} catch (IOException e) {
			isenable = false;
			logger.error("执行拉取配置失败", e);
			e.printStackTrace();
		}
		return null;
	}
	
	private void covertProperty(FetchDto fetchDto) {
		if (fetchDto != null) {
			List<ConfigItem> configItems = fetchDto.getItems();
			if (configItems != null && configItems.size() > 0) {
				for (ConfigItem configItem : configItems) {
					this.getProperties().put(configItem.getKey(), configItem.getValue());
				}
			}
			AppInstance.setVersion(fetchDto.getVersion());
		}
	}
}
